<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .light {
            height: 100px;
            width: 100px;
            border-radius: 50%;
        }
        .nolight {
            background-color: #555;
        }
        .g {
            background-color: green;
        }
        .y {
            background-color: yellow;
        }
        .r {
            background-color: red;
        }
    </style>
</head>
<body>
    <div class="light nolight"></div>
    <div class="light nolight"></div>
    <div class="light nolight"></div>
    <button id="open">开灯</button>
    <script>
        // 1.模拟交通灯：3个圆盒子模拟3个交通灯，然后每3秒切换灯亮的颜色

        const light = document.getElementsByClassName("light")
        const open = document.querySelector("#open")

        open.onclick = function () {
            let index = 0;
            setInterval(function() {
                if (index == 0) {
                    light[0].setAttribute("class", "light g")
                    light[1].setAttribute("class", "light nolight")
                    light[2].setAttribute("class", "light nolight")
                    index++;
                }
                else if (index == 1) {
                    light[0].setAttribute("class", "light nolight")
                    light[1].setAttribute("class", "light y")
                    light[2].setAttribute("class", "light nolight")
                    index++;
                } else if (index == 2) {
                    light[0].setAttribute("class", "light nolight")
                    light[1].setAttribute("class", "light nolight")
                    light[2].setAttribute("class", "light r")
                    index = 0;
                }     
            }, 5 * 1000)
        }

        
        
    </script>
</body>
</html>